#include <iostream>
#include <map>
#include <vector>
#include <sstream>
#include <deque>
#include <string>
#include <string.h>

using namespace std;

map<string, int> idPerson;

vector< vector<int> > paper; // list (list of id of arthors) of papers
vector<	string > paperRaw;

vector< vector<int> > listPaper;
vector< int > number;

int P, N, ntest;

void BFS()
{
	number.resize(N, -1);
	int start = idPerson["Erdos, P."];
	number[start] = 0;

	deque<int> q;
	while (!q.empty())
	{
		int u = q.front();
		q.pop_front();

		for (int i = 0; i < listPaper[u].size(); i++) 
		{
			int nPaper = listPaper[u][i];
			for (int j = 0; j < paper[nPaper].size(); j++)
			{
				int v = paper[nPaper][j];
				if (number[v] == -1)
				{
					number[v] = number[u]+1;
					q.push_back(v);
				}
			}
		}
	}

}

int main()
{
	cin >> ntest;
	while (0 < ntest--)
	{
		cin >> P >> N;

		paperRaw.clear();
		for (int i = 0; i < P; i++) 
		{
			string s;
			getline(cin, s);
			paperRaw.push_back(s);
		}

		idPerson.clear();
		for (int i = 0; i < N; i++) 
		{
			string s;
			getline(cin, s);
			idPerson[s] = i;
		}

		paper.clear();
		for (int i = 0; i < P; i++) 
		{
			stringstream ss(paperRaw[i]);

			string s1, s2;
			vector<int> arthors(0);
			while (true)
			{
				ss >> s1 >> s2;
				s1 = s1 + s2;
				s1.erase(s1.end()-1);

				if (idPerson.find(s1) != idPerson.end()) arthors.push_back(idPerson[s1]);

				if (s2[s2.end()-1] == '.') break;
			}
			paper.push_back(arthors);
		}

		BFS();
	}
	return 0;
}

